<template>
    <el-form :model="form" label-width="120px" :rules="rules" ref="formRef" class="add-article-form">
        <el-form-item label="标题">
            <el-input v-model="form.title" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="简介">
            <el-input v-model="form.description" placeholder="请输入简介"/>
        </el-form-item>
        <el-form-item label="分类">
            <el-select v-model="form.category_id" placeholder="请选择分类" clearable>
                <el-option label="请选择分类" :value="null" disabled />
                <el-option v-for="item in articleCategoryList" :label="item.name" :value="item.id" />
            </el-select>
        </el-form-item>
        <el-form-item label="封面图" prop="cover">
        <el-upload
          :action="action"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="coverRemove"
          name="file"
          :headers="{ 'Authorization':  token }"
          :on-success="handleSuccess"
          :before-upload="beforeAvatarUpload"
          accept=".jpg,.jpeg,.png,.gif"
          :show-file-list="false"
          :on-exceed="handleExceed"
        >
          <div v-if="form.cover">
            <img :src="form.cover" alt="封面图" style="max-height: 146px;" />
          </div>
          <div v-else>
            <el-icon><Plus /></el-icon>
          </div>
        </el-upload>
        </el-form-item>

        <el-form-item>
            <Editor v-if="editorVisible" :formData="form" @content="content"  label="内容" prop="content"/>
        </el-form-item>

        <el-form-item label="排序">
            <el-input v-model="form.sort" type="number" placeholder="请输入排序" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
            </el-radio-group>
        </el-form-item>
    </el-form>
</template>
<script setup>
import {onMounted, reactive, ref, watch} from 'vue'
import { ElMessage } from 'element-plus'
import  Editor from '@/components/Editor.vue'
import { Plus } from '@element-plus/icons-vue'

const token = localStorage.getItem('token');
const action = '/adminApi/upload'
// 表单元素的引用
const formRef = ref(null);
// 定义组件接收的属性
const props = defineProps({
    formData: {
      type: Object, // 表单数据对象
      default: () => null // 默认值为 null
    },
    isEdit: {
      type: Boolean, // 是否为编辑模式
      default: false // 默认值为 false
    },
    articleCategoryList: {
      type: Object, // 文章分类列表
      default: () => {} // 默认值为空对象
    }
});

const editorVisible = ref(false); // 控制编辑器的显示状态

onMounted(() => {
  // 页面加载完成后显示编辑器
  editorVisible.value = true;
});

// 初始化表单数据
const form = reactive({
  title:  props.formData?.title || '',
  description: props.formData?.description || '',
  category_id: props.formData?.description || null,
  sort: props.formData?.sort || 0,
  cover:props.formData?.cover || '',
  content:props.formData?.cover || '',
  status:props.formData?.status || 1
})

// 监听formData变化，更新表单数据
watch(() => props.formData, (newVal) => {
    if (newVal) {
      Object.assign(form, newVal);
    }
  }, { immediate: true }
);

// 验证规则
const rules = {
    title: [
      { required: true, message: '请输入标题', trigger: 'blur' },
      { min: 2, max: 20, message: '标题长度在2到20个字符之间', trigger: 'blur' }
    ],
    category_id: [
      { required: true, message: '请选择分类', trigger: 'change' }
    ],
    status: [
      { required: true, message: '请选择状态', trigger: 'change' }
    ]
};

const validateForm = async () => {
    try {
      await formRef.value.validate();
      return true;
    } catch (error) {
      ElMessage.error('请检查表单填写是否正确');
      return false;
    }
};


// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  Object.assign(form, {
    title:'',
    description:'',
    category_id: null,
    sort: 0,
    cover:'',
    content:'',
    status:1
  });
};

const beforeAvatarUpload = (file) => {
    const isImage = file.type.startsWith('image/'); // 检查 MIME 类型是否以 "image/" 开头
    if (!isImage) {
      ElMessage.error('只能上传图片!');
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2000; // 限制图片大小为 2MB
    if (!isLt2M) {
      ElMessage.error('上传图片大小不能超过 2000MB!');
      return false;
    }
    return true;
  };

const handleSuccess = (response) => {
    if (response.code === 1) {
      form.cover = response.data; // 假设返回的数据中有文件的URL
      ElMessage.success('上传成功');
    } else {
      ElMessage.error('上传失败');
    }
};

const coverRemove = (file, fileList) => {
    form.cover = '';
};

//内容发生变化时触发 子组件调用
const content = (e)=>{
    console.log('form.content', e);
    form.content = e;
}

defineExpose({
    formRef,
    form,
    validateForm,
    resetForm
});

</script>
<style scoped>

</style>
